const express = require('express')
const app = express();
const path = require('path')

// 处理请求中间件
app.use(express.urlencoded())
app.use(express.json())

app.get("/userInfo", (req, res) => {
  //设置允许允许跨域的地址集合
  const allow = ["http://127.0.0.1:5500", "http://127.0.0.1:5501", "http://127.0.0.1:5502"]
  console.log(req.headers.origin); //拿到请求的来源地址
  // 判断   用获取的地址和允许的地址数组进行比较
  //用includes（）查找方法对比，有就允许跨域。   如果有返回true 进去
  if (allow.includes(req.headers.origin)) {
    res.set("Access-Control-Allow-Origin", req.headers.origin)
  }

  res.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "xiaoM",
      age: 18,
      sex: "男"
    }
  })
})


app.get("/user", (req, res) => {
    // console.log(req.query);
    const {
      userId
    } = req.query;
  
    //如果查询失败
    if (userId !== "001") {
      return res.send({
        code: 10001,
        msg: "查询失败",
        data: null
      })
    }
    //查询成功 响应
    res.send({
      code: 10000,
      msg: "查询成功",
      data: {
        name: "xiaoA",
        age: 18,
        sex: "男"
      }
    })
  
  })

//jsonp请求接口
app.get("/getUser", (req, res) => {
  console.log(req.query);
  const {
    userId,
    cb
  } = req.query;

  const data = {
    code: 10000,
    msg: "查询成功",
    data: {
      name: "xiaoA",
      age: 18,
      sex: "男"
    }
  }
  //这里会返回请求传输的callback函数调用，返回data这个数据对象
  res.send(`${cb}(${JSON.stringify(data)})`)
})

//加载静态资源
app.get('/1',(req,res)=>{
    const filePath = path.resolve(__dirname,'./01-JSONP解决跨域.html')

    res.sendFile(filePath)
})

app.get('/2',(req,res)=>{
  const filePath = path.resolve(__dirname,'./cors跨域.html')

  res.sendFile(filePath)
})


app.listen('3030',()=>{
    console.log(
        '启动成功 地址：http://127.0.0.1:3030  ');
})